package com.codingfuture.erp_system.web.controller;

import com.codingfuture.erp_system.entity.Emp;
import com.codingfuture.erp_system.service.LoginService;
import com.codingfuture.erp_system.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/v2")
@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;


    /**
     * 登录验证
     *
     * @param username
     * @param password
     * @param session
     * @return 成功？失败？
     */
    @PostMapping("/login")
    public Result login(String username, @RequestParam("pwd") String password, HttpSession session) {

        if (username != null && password != null) {
            Emp emp = loginService.login(username, password);
            if (emp != null) {
                session.setAttribute("name", emp.getName());
                session.setAttribute("uuid", emp.getUuid());
                return Result.ok();
            } else {
                return Result.error(401, "用户名，密码错误");
            }
        }
        return Result.error(401, "请输入用户名密码");
    }


    /**
     * 获取用户名
     *
     * @param session
     * @return 用户名
     */
    @PostMapping("/login_showName")
    public Map loginShowName(HttpSession session) {
        Object name = session.getAttribute("name");
        Map<String, Object> map = new HashMap<>();
        map.put("code", "200");
        map.put("rows", name);
        map.put("msg", "请求成功");
        return map;
    }


    /**
     * 更新密码
     *
     * @param oldPwd
     * @param newPwd
     * @param session
     * @return 成功？失败？
     */
    @PostMapping("/updatepwd")
    public Result updatePwd(@RequestParam("oldPwd") String oldPwd,
                            @RequestParam("newPwd") String newPwd,
                            HttpSession session) {
        if (oldPwd.equals(newPwd)) {
            return Result.error(401, "新密码和旧密码重复，请重新输入。");
        } else {
            Object uuid = session.getAttribute("uuid");
            int row = loginService.updatePwd(oldPwd, newPwd, uuid);
            if (row == 1) {
                return Result.ok();
            } else {
                return Result.error(401, "密码修改失败。");
            }
        }
    }

    //

    /**
     * 退出
     *
     * @param session
     * @return 成功？失败？
     */
    @GetMapping("//login_loginOut")
    public Result loginOut(HttpSession session) {
        session.removeAttribute("name");
        session.removeAttribute("uuid");
        return Result.ok();
    }
}
